// API 服务文件
import type { User, LoginRequest, RegisterRequest } from '@/types'
import { request } from '@/config/api'

// 用户API
export const userAPI = {
  // 获取所有用户
  async getUsers(): Promise<User[]> {
    return request<User[]>('/users')
  },

  // 根据ID获取用户
  async getUserById(id: string): Promise<User> {
    return request<User>(`/users/${id}`)
  },

  // 用户登录验证
  async login(credentials: LoginRequest): Promise<{ user: User; token: string; refreshToken: string }> {
    const response = await request<{ success: boolean; message: string; data: { user: User; tokens: { accessToken: string; refreshToken: string } } }>('/auth/login', {
      method: 'POST',
      body: JSON.stringify(credentials),
    })
    return {
      user: response.data.user,
      token: response.data.tokens.accessToken,
      refreshToken: response.data.tokens.refreshToken
    }
  },

  // 用户注册
  async register(userData: Omit<RegisterRequest, 'confirmPassword'>): Promise<{ user: User; token: string; refreshToken: string }> {
    const registerData = {
      username: userData.username,
      email: userData.email,
      password: userData.password,
      firstName: userData.firstName,
      lastName: userData.lastName,
      phone: userData.phone || '',
    }

    const response = await request<{ success: boolean; message: string; data: { user: User; tokens: { accessToken: string; refreshToken: string } } }>('/auth/register', {
      method: 'POST',
      body: JSON.stringify(registerData),
    })
    return {
      user: response.data.user,
      token: response.data.tokens.accessToken,
      refreshToken: response.data.tokens.refreshToken
    }
  },

  // 更新用户信息
  async updateUser(id: string, userData: Partial<User>): Promise<User> {
    return request<User>(`/users/${id}`, {
      method: 'PUT',
      body: JSON.stringify({
        ...userData,
        updatedAt: new Date().toISOString(),
      }),
    })
  },

  // 删除用户
  async deleteUser(id: string): Promise<void> {
    return request<void>(`/users/${id}`, {
      method: 'DELETE',
    })
  },

  // 检查用户名是否存在（后端会处理重复验证）
  async checkUsername(username: string): Promise<boolean> {
    // 暂时返回false，让后端处理重复验证
    return false
  },

  // 检查邮箱是否存在（后端会处理重复验证）
  async checkEmail(email: string): Promise<boolean> {
    // 暂时返回false，让后端处理重复验证
    return false
  },
}

// 会话API
export const sessionAPI = {
  // 创建会话（登录）
  async createSession(userId: string): Promise<any> {
    const sessionData = {
      userId,
      createdAt: new Date().toISOString(),
      expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(), // 24小时后过期
    }

    return request<any>('/sessions', {
      method: 'POST',
      body: JSON.stringify(sessionData),
    })
  },

  // 获取用户会话
  async getUserSessions(userId: string): Promise<any[]> {
    return request<any[]>(`/sessions?userId=${userId}`)
  },

  // 删除会话（登出）
  async deleteSession(sessionId: string): Promise<void> {
    return request<void>(`/sessions/${sessionId}`, {
      method: 'DELETE',
    })
  },
}